/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.gui.knowledgeBase;

import jade.gui.GuiEvent;

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashSet;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.text.html.HTMLDocument;

import org.htmlparser.Parser;
import org.htmlparser.beans.StringBean;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.lexer.Page;
import org.utc.ia04.antsontheweb.knowledgeBase.KnowledgeBaseAgent;
import org.utc.ia04.antsontheweb.utilities.KnowledgeBaseRequest;
import org.utc.ia04.antsontheweb.utilities.Requete;

public class KnowledgeBaseLearningFrame extends JFrame implements PropertyChangeListener
{
	//serialVersionUID
	private static final long serialVersionUID = 1146363395296778226L;
	
	//Attribut
	KnowledgeBaseLearningGuiAgent myAgent;
	JEditorPane viewer;
	JTextField adresse;
	JComboBox typeSite;
	
	//METHODE
	public KnowledgeBaseLearningFrame(KnowledgeBaseLearningGuiAgent agent)
	{
		super();
		initialiseFrame();
		myAgent = agent;
		myAgent.addPropertyChangeListener(this);
	}
	
	public void initialiseFrame()
	{
		//Initialisation de la fenêtre
		setTitle("Learning GUI...");
		setSize(400, 500);
		setVisible(true);
		
		//Conteneur principal
		JPanel panel = new JPanel();
		setContentPane(panel);
		BorderLayout layout = new BorderLayout();
		panel.setLayout(layout);
		
		//Barre d'adresse
		adresse = new JTextField("http://www.utc.fr");
		panel.add(adresse, BorderLayout.NORTH);
		adresse.addActionListener(new ChangePageListener(this));

		//Page Web
		viewer = new JEditorPane ();
		JScrollPane subPanel = new JScrollPane(viewer);
		panel.add(subPanel, BorderLayout.CENTER);
		
		viewer.setContentType ( "text/html" );
		viewer.addHyperlinkListener(new ChangePageListener(this));
		viewer.setEditable(false);
		loadPage("http://www.utc.fr");
		
		//Barre de selection de type
		JPanel submitPanel = new JPanel();
		panel.add(submitPanel, BorderLayout.SOUTH);
		BorderLayout submitLayout = new BorderLayout();
		submitPanel.setLayout(submitLayout);
			
		typeSite = new JComboBox(new Object[]{ KnowledgeBaseAgent.BUYING_SITE_NAME, KnowledgeBaseAgent.OTHER_NAME });
		submitPanel.add(typeSite, BorderLayout.CENTER);
			
		JButton submit = new JButton("Learn !");
		submitPanel.add(submit, BorderLayout.EAST);
		submit.addActionListener(new LearnActionListener(this));
		
		JButton tests = new JButton("Test !");
		submitPanel.add(tests, BorderLayout.WEST);
		tests.addActionListener(new TestActionListener(this));
	}

	public void setAdresse(String _adresse)
	{
		adresse.setText(_adresse);
	}
	
	public void propertyChange(PropertyChangeEvent evt)
	{
		String message = evt.getPropertyName();
		if(message.equals(KnowledgeBaseLearningGuiAgent.ERROR_OCCURED)) JOptionPane.showMessageDialog(this, message, "Avertissement", JOptionPane.ERROR_MESSAGE);
		else JOptionPane.showMessageDialog(this, message, "Notification", JOptionPane.INFORMATION_MESSAGE);
	}

	public void loadPage()
	{
		loadPage(adresse.getText());
	}
	
	public void loadPage(String urlStr)
	{
		try
		{
			viewer.setPage(urlStr);
		}
		catch(Exception e)
		{
			System.out.println ("Page " + urlStr + " introuvable : " + e.toString());
		}
	}
	
	public HTMLDocument getDocument()
    {
            return (HTMLDocument)viewer.getDocument();
    }

	
	public void sendKeyword(int objectif, int associatedRequeteCode)
	{	
		HashSet<String> keywords = getKeywordFromViewer();
		if(keywords == null)
			JOptionPane.showMessageDialog(this, "Operation failed...", "Avertissement", JOptionPane.ERROR_MESSAGE);
		else
		{
			KnowledgeBaseRequest kbRequete = new KnowledgeBaseRequest(typeSite.getSelectedIndex(), keywords);
			Requete requete = new Requete(associatedRequeteCode, kbRequete.serialize());
			
			GuiEvent ev = new GuiEvent(myAgent, objectif);
			ev.addParameter(requete.serialize());
			myAgent.postGuiEvent(ev);
		}
	}
	
	private HashSet<String> getKeywordFromViewer()
	{
		try
		{
			//A) Récupérer les chaines affichées
			HashSet<String> keywords = new HashSet<String>();
			HTMLDocument doc = (HTMLDocument)viewer.getDocument();
			Page page = new Page(doc.getText(0, doc.getLength()));
			Lexer lexer = new Lexer(page);
			Parser parser = new Parser(lexer);
			
			StringBean sb = new StringBean();
			sb.setCollapse(true);
			
			parser.visitAllNodesWith(sb);
			String result = sb.getStrings();
			
			//B) Découper selon les espaces
			String[] decoupe = result.split("\\p{Blank}");
			for(int i = 0; i < decoupe.length; ++i)
				keywords.add(decoupe[i]);
			
			//C) Envoie du résultat
			return keywords;
		}
		catch(Exception e)
		{
			System.out.println("Erreur parsing html : " + e.toString());
			return null;
		}
	}
}
